<template>
  <div>
    <!-- 物资服务查看总览 -->
    <ZrPmsCheckMaterials
      v-if="shouldShowCheckMaterials"
      @initIframeHeight="initIframeHeight"
      @initNextInfo="initNextInfo"
    />
    <!-- 校验清单 -->
    <div v-else>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane v-for=" item in prjInfos " :key="item.prjId" :label="item.prjId" :name="item.prjId">
          <span slot="label">
            {{ item.prjCode }}
            <i v-if="getStatus(item.prjId) === 'success'" style="color: #07C160" class="el-icon-circle-check" />
            <i v-if="getStatus(item.prjId) === 'loading'" class="el-icon-loading" />
            <i v-if="getStatus(item.prjId) === 'error'" style="color: #c53f3f " class="el-icon-circle-close" />
          </span>
          <el-table :data="checkList.data" border max-height="300">
            <el-table-column type="index" label="序号" />
            <el-table-column prop="description" label="校验内容" width="300" />
            <el-table-column label="是否完成" width="80" align="center">
              <template slot-scope="{row}">
                <div v-if="!checkData[activeName]">
                  <i class="el-icon-loading" />
                </div>
                <div v-else-if="checkData[activeName].find(item => item.code === row.code).check">
                  <i class="el-icon-circle-check" style="color: #07C160" />
                </div>
                <div v-else>
                  <i class="el-icon-circle-close" style="color: #c53f3f" />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="备注">
              <template slot-scope="{row}">
                <div v-if="!checkData[activeName]" />
                <div
                  v-else-if="checkData[activeName].find(item => item.code === row.code).confirm == 'P'"
                  v-html="checkData[activeName].find(item => item.code === row.code).msg"
                />
                <div v-else-if="checkData[activeName].find(item => item.code === row.code).check" />
                <div v-else v-html="checkData[activeName].find(item => item.code === row.code).msg" />
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <next-page
        v-if="nextVisible"
        ref="nextPage"
        :visible.sync="nextVisible"
        :activity-inst-id="workDetail.activityInstID"
        :process-inst-id="workDetail.processInstID"
        :activity-def-id="workDetail.activityDefID"
        :process-def-name="workDetail.processDefName"
        :route="getNewRoute"
        @selected="close"
        @doNextEntity="nextPageRes"
      />
      <div style="text-align: center;margin-top: 20px">
        <el-button class="pms-zr-button-primary pms-zr-ClosedBtn" size="small" @click="doNext">确认</el-button>
      </div>
      <!-- 确认弹框二次校验 -->
      <DialogConfirm v-if="dialogVisible" :message="dialogMessage" @changeStatus="changeMsg" />
    </div>

  </div>
</template>
<script>
import DialogConfirm from '@/views/acceptanceManagement/materialServiceBind/components/dialogConfirm.vue'
import {
  doNextBatchFLowApi,
  executeVerificationAccFormApi,
  executeVerificationApi,
  getVerificationListApi,
  getPrjDetailApi
} from '@/api/acceptance'
import NextPage from '@/components/nextPerson/NextPage.vue'
import { doNextFLowApi, getWFWorkItemApi } from '@/api/acceptanceManagement/acceptanceMange'
import { disableScroll, enableScroll, getQueryObject, msgInfoEl } from '@/utils'
import ZrPmsCheckMaterials from '@/views/acceptance/checkMaterials/ZrPmsCheckMaterials.vue'
export default {
  name: 'InteriorVerify',
  components: { NextPage, ZrPmsCheckMaterials, DialogConfirm },
  data() {
    return {
      activeName: '',
      prjInfos: [],
      checkList: {},
      checkData: {},
      nextVisible: false,
      workDetail: {},
      single: '',
      dialogVisible: false,
      dialogMessage: ['仅支持对校验全部通过的项目提交流程,校验通过项目编码:'],
      getPrjDetailObj: {},
      TablePrjInfo: []
    }
  },
  computed: {
    shouldShowCheckMaterials() {
      return this.$route.query.checkMaterials === 'true'
    },
    getNewRoute() {
      let _routes = '1'
      const { bizState } = this.workDetail.bizObject
      const showsOne = bizState === 'F1' && this.getPrjDetailObj.manageMode === '03'
      const showsTwo = bizState === 'F1' && this.getPrjDetailObj.manageMode === '01'
      if (showsOne && (this.TablePrjInfo[0].prjType === 'W' || this.TablePrjInfo[0].buildModes === '07')) {
        _routes = '3'
      } else if (showsTwo && (this.getPrjDetailObj.prjType === 'W' || (this.getPrjDetailObj.buildModes === '07' && this.getPrjDetailObj.isMaintain === '1'))) {
        _routes = '3'
      } else {
        _routes = this.getNewRouteTwo
      }
      return _routes
    },
    
    getNewRouteTwo(){
      const { bizState } = this.workDetail.bizObject
      return +this.getPrjDetailObj.isNewAcceptance === 1&&bizState==='F1'&&this.getPrjDetailObj.manageMode === '31'?'3':'1'
    }
  },
  async created() {
    const { prjInfos, single } = getQueryObject()
    this.single = single
    // 如果说物资查看总览下一步成功了在进行校验清单
    // this.prjInfos = JSON.parse(prjInfos)
    this.TablePrjInfo = JSON.parse(window.sessionStorage.getItem('TableprjInfos'))
    this.prjInfos = JSON.parse(window.sessionStorage.getItem('prjInfos'))
    if (this.prjInfos.length < 1) {
      this.prjInfos = JSON.parse(window.localStorage.getItem('prjInfos'))
    }
    this.activeName = this.prjInfos[0].prjId
    this.getCheckList()
    this.getWorkDetail()
    if (!this.shouldShowCheckMaterials) {
      this.$nextTick(() => {
        const params = {
          height: 400,
          type: 'checkListStle'
        }
        console.log(params, 'checkListStle=>初始化发送校验清单高度')
        window.parent.postMessage(params, this.$fixIframeArr())
      })
    }
  },
  methods: {
    // 获取高度并设置
    initIframeHeight(data) {
      this.$nextTick(() => {
        const params = {
          height: this.shouldShowCheckMaterials ? data : 400,
          type: 'initMaterialsInfo'
        }
        window.parent.postMessage(params, this.$fixIframeArr())
      })
    },
    // 物资查看总览点击下一步是否成功
    initNextInfo(data) {
      this.$nextTick(() => {
        const params = {
          doNext: data,
          type: 'initNextInfo',
          single: this.single
        }
        window.parent.postMessage(params, this.$fixIframeArr())
      })
    },
    close() {
      // this.dialogClosed()
    },
    getInfo(id) {
      if (id) {
        return 'success'
      }
      return 'error'
    },
    doNext() {
      this.dialogMessage = []
      this.dialogMessage.push('仅支持对校验全部通过的项目提交流程,校验通过项目编码:')
      // todo 如果没有校验成功的不允许提交
      const check = this.prjInfos.some(item => this.getStatus(item.prjId) === 'success')
      // 获取校验成功的项目编码
      const result = this.prjInfos.every(item => {
        if (this.getStatus(item.prjId) === 'success') {
          this.dialogMessage.push(item.prjCode)
          return true
        } else {
          return false
        }
      })
      if (check) {
        // window.parent.postMessage({ type: 'closeCheckDialog' }, '*')
        if (this.getPrjDetailObj.manageMode === '31' || this.prjInfos[0].manageMode == '31') {
          this.dialogVisible = true
        } else {
          setTimeout(() => {
            this.nextVisible = true
            this.dialogEl('nextPage')
          }, 3)
        }
      } else {
        msgInfoEl({
          type: 'error',
          message: '没有通过校验的项目'
        }, 3000)
      }
    },
    changeMsg(status) {
      this.dialogVisible = false
      if (status) {
        setTimeout(() => {
          this.nextVisible = true
          this.dialogEl('nextPage')
        }, 3)
      }
    },
    // 将弹框挂载在最外层
    dialogEl(refName) {
      // 将弹框挂载在最外层
      const contentBody = window.top.document.body
      this.$nextTick(() => {
        const dialogModal = document.querySelector('.v-modal')
        const elBody = this.$refs[refName].$el
        dialogModal.style.zIndex = 3000
        elBody.style.zIndex = 3001
        contentBody.appendChild(elBody)
        contentBody.appendChild(dialogModal)
        // disableScroll(contentBody)
      })
    },
    // 关闭弹框
    dialogClosed() {
      this.nextVisible = false
      const contentBody = window.top.document.body
      enableScroll(contentBody)
    },
    async getWorkDetail() {
      const result = await getWFWorkItemApi(this.prjInfos[0].workItemId)
      this.workDetail = result.data
      this.getPrjDetail(this.workDetail.bizObject.prjId)
    },
    async getPrjDetail(id) {
      const res = await getPrjDetailApi(id)
      this.getPrjDetailObj = res.data
    },
    getStatus(id) {
      if (!this.checkData[id]) {
        return 'loading'
      }
      const result = this.checkStatus(this.checkData[id])
      if (result) {
        return 'success'
      }
      return 'error'
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    async getCheckList() {
      const params = {
        nodeState: `${this.prjInfos[0].bizState || this.prjInfos[0].nodeState}_FORM`,
        prjId: this.prjInfos[0].prjId
      }
      const result = await getVerificationListApi(params)
      this.checkList = result.data
      this.prjInfos.map(item => {
        this.getCheckData(item)
      })
    },
    async getCheckData(item) {
      const params = {
        prjInfo: item,
        ysCode: this.checkList.ysCode
      }
      const result = await executeVerificationAccFormApi(params)
      this.$set(this.checkData, item.prjId, result.data)
    },
    checkStatus(arr) {
      return !arr.some(item => !item.check)
    },
    async nextPageRes(data) {
      console.log(data)
      const prjId = this.prjInfos.map(item => item.prjId).join(',')
      const workItemIds = this.prjInfos.map(item => item.workItemId).join(',')
      const params = {
        'prjId': prjId,
        'userIds': data.empId,
        'route': this.getNewRoute, // 下一步页面
        'wfXpath': [], // 暂时不传
        'opinion': data.opinion,
        'nextSceneId': data.nextSceneId, // 先不传
        'nodeId': data.nodeId,
        'detailId': data.detailId, // 先不传
        'route1': '1', // 决算页面
        'activityDefId': data.actDefId, // 当前节点
        'finish': data.finish, // 当前节点
        'templateId': data.nTemplateId
      }
      console.log(this.single)
      if (this.single) {
        params.workItemId = workItemIds
        doNextFLowApi(params).then(res => {
          if (+res.code === 200) {
            window.parent.postMessage({ type: 'interiorVerify' }, this.$fixIframeArr())
          }
        })
      } else {
        params.workItemIds = workItemIds
        doNextBatchFLowApi(params).then(res => {
          if (+res.code === 200) {
            window.parent.postMessage({ type: 'interiorVerify' }, this.$fixIframeArr())
          }
        })
      }
      console.log(params)
    }
  }
}
</script>
<style scoped lang='scss'></style>
